package io.potato.ts.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * 登录次数限制
 * author: timl
 * time: 2019-4-27 11:20
 */
@Component
@Slf4j
public class LoginTryLimit {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "sms_login_try_times:";

    private static final String KEY_PREFIX_LOCK = "sms_login_try_locks:";

    private long maxTryTimes = 6L;

    private int lockDuration = 120;

    public long getTryTimes(String username) {
        String cacheKey = getUserCacheKey(username);
        long tryTimes = 1L;
        if (redisTemplate.hasKey(cacheKey)) {
            tryTimes = redisTemplate.opsForValue().increment(cacheKey);
        }
        return tryTimes;
    }

    public void setTryTimes(String username) {
        String cacheKey = getUserCacheKey(username);
        redisTemplate.opsForValue().set(cacheKey, "1", Duration.ofMinutes(10));
    }

    public void clearTryTimes(String username) {
        String cacheKey = getUserCacheKey(username);
        redisTemplate.delete(cacheKey);
    }

    public boolean isOverlimit(long tryTimes) {
        return  (tryTimes > maxTryTimes);
    }

    public void lock(String username) {
        redisTemplate.opsForValue().set(getLockCacheKey(username), "1", Duration.ofMinutes(120));
    }

    public boolean isLocked(String username) {
        return redisTemplate.hasKey(getLockCacheKey(username));
    }

    public int getLockDuration() {
        return lockDuration;
    }

    private String getUserCacheKey(String username) {
        return KEY_PREFIX + username;
    }

    private String getLockCacheKey(String username) {
        return  KEY_PREFIX_LOCK + username;
    }


}
